package com.lzh.lzhframework.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lzh.lzhframework.dao.FeedbackMapper;
import com.lzh.lzhframework.domain.ResponseResult;
import com.lzh.lzhframework.domain.dto.feedback.UpdateFeedbackReadStatusDto;
import com.lzh.lzhframework.domain.entity.FeedbackEntity;
import com.lzh.lzhframework.domain.entity.mongo.UserFeedbackEntity;
import com.lzh.lzhframework.domain.vo.feedback.NoticeMsgVo;
import com.lzh.lzhframework.service.FeedbackService;
import com.lzh.lzhframework.service.MessageService;
import com.lzh.lzhframework.utils.SecurityUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 消息服务接口实现类
 *
 * @Author luzhiheng
 * @Date 2023/12/10 19:00
 */
@Service
public class MessageServiceImpl implements MessageService {

    @Resource
    private MongoTemplate mongoTemplate;

    @Resource
    private FeedbackMapper feedbackMapper;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Override
    public List<NoticeMsgVo> queryUnreadMsg() {
        Long userId = SecurityUtils.getUserId();

        Query query = Query.query(Criteria.where("admin_id").is(userId)
                .andOperator(Criteria.where("is_read").is(false)));
        List<UserFeedbackEntity> userFeedbackEntityList = mongoTemplate.find(query, UserFeedbackEntity.class);

        List<Long> feedbackIdList = userFeedbackEntityList.stream().map(UserFeedbackEntity::getFeedbackId).collect(Collectors.toList());

        List<FeedbackEntity> feedbackEntityList = new ArrayList<>();
        if (feedbackIdList.size() > 0) {
            LambdaQueryWrapper<FeedbackEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(FeedbackEntity::getId, feedbackIdList);
            feedbackEntityList = feedbackMapper.selectList(queryWrapper);
        }
        List<NoticeMsgVo> noticeMsgVoList = feedbackEntityList.stream().map(NoticeMsgVo::new).collect(Collectors.toList());

        rabbitTemplate.convertAndSend("feedback.read", "feedback.update.read", new UpdateFeedbackReadStatusDto(userId, feedbackIdList));
        return noticeMsgVoList;
    }
}